package com.aiton.bamin.changtukepiao.Zeverything;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.utils.UILUtils;
import com.aiton.bamin.changtukepiao.R;
import com.aiton.bamin.changtukepiao.Zeverything.constant.EverythingConstant;
import com.aiton.bamin.changtukepiao.models.Zabout_user.User;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.File;
import java.io.FileNotFoundException;

import cz.msebera.android.httpclient.Header;

public class MineInfoActivity extends AppCompatActivity implements View.OnClickListener {

    private String mPhoneNum;
    private TextView mTextView_phone;
    private final int PIC_FROM＿LOCALPHOTO = 0;
    private final int PIC_FROM_CAMERA = 1;
    private Uri photoUri;
    private String mId;
    private ImageView mImageView_headIcon;
    private String mImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_info);
        initSp();
        findID();
        initUI();
        setListener();
    }

    private void setListener() {
        findViewById(R.id.findBackPassword).setOnClickListener(this);
        findViewById(R.id.button_zuxiao).setOnClickListener(this);
        findViewById(R.id.imageView_back).setOnClickListener(this);
        findViewById(R.id.rela_update_icon).setOnClickListener(this);
    }

    private void initUI() {
        mTextView_phone.setText(mPhoneNum.substring(0,3)+"****"+mPhoneNum.substring(7,11));
        if ("".equals(mImage)){
            mImageView_headIcon.setImageResource(R.mipmap.a02);
        }else{
            UILUtils.displayImageNoAnimNoCache(mImage, mImageView_headIcon, false);
        }
    }

    private void findID() {
        mTextView_phone = (TextView) findViewById(R.id.textView_phone);
        mImageView_headIcon = (ImageView) findViewById(R.id.imageView_headIcon);
    }

    private void initSp() {
        SharedPreferences sp = getSharedPreferences("isLogin", Context.MODE_PRIVATE);
        mPhoneNum = sp.getString("phoneNum", "");
        mId = sp.getString("id", "");
        mImage = sp.getString("image", "");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PIC_FROM_CAMERA: // 拍照
                try {
                    cropImageUriByTakePhoto();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case PIC_FROM＿LOCALPHOTO:
                try {
                    if (photoUri != null) {
                        Bitmap bitmap = decodeUriAsBitmap(photoUri);
                        mImageView_headIcon.setImageBitmap(bitmap);
                        postFile(photoUri);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    public void postFile(Uri uploadFile) {
        String path = uploadFile.getPath();
        Log.e("postFile", "path" + path);
        File file = new File(path);
        String actionUrl = "http://120.24.46.15:8080/bmpw/account/updateIcon";
        if (file.exists() && file.length() > 0) {
            RequestParams params = new RequestParams();
            params.put("account_id", mId);
            Log.e("postFile", "用户ID" + mId);
            try {
                params.put("data", file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            asyncHttpClient.post(actionUrl, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    Log.e("onSuccess: ", "---> " + new String(responseBody));
                    User user = GsonUtils.parseJSON(new String(responseBody), User.class);
                    SharedPreferences sp = getSharedPreferences("isLogin", MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("image", user.getContains().getImage());
                    Log.e("onResponse", "图片地址" + user.getContains().getImage());
                    edit.commit();
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.e("onFailure", "失败");
                }
            });
        } else {
            Toast.makeText(MineInfoActivity.this, "文件不存在", Toast.LENGTH_LONG).show();
        }

    }

    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()){
            case R.id.rela_update_icon:
                setPopupWindows();
                break;
            case R.id.findBackPassword:
                intent.setClass(MineInfoActivity.this,UpdatePasswordActivity.class);
                intent.putExtra("findBackPassword", "findBackPassword");
                startActivity(intent);
                animFromSmallToBigIN();
                break;
            case R.id.button_zuxiao:
                AlertDialog.Builder builder = new AlertDialog.Builder(MineInfoActivity.this);
                builder.setTitle("提醒");
                builder.setMessage("确定要退出吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SharedPreferences sp = getSharedPreferences("isLogin", Context.MODE_PRIVATE);
                        SharedPreferences.Editor edit = sp.edit();
                        edit.clear();
                        edit.commit();
                        finish();
                        animFromBigToSmallOUT();
                        setResult(EverythingConstant.ISUPDATEICON);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
                break;
            case R.id.imageView_back:
                finish();
                animFromBigToSmallOUT();
                break;
            case R.id.click_local:
                if (ContextCompat.checkSelfPermission(MineInfoActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(MineInfoActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            EverythingConstant.RequestAndResultCode.PERMISSION_READ_EXTERNAL_STORAGE);
                } else {
                    doHandlerPhoto(PIC_FROM＿LOCALPHOTO);// 从相册中去获取
                    mPopupWindow.dismiss();
                }
                break;
            case R.id.click_camera:
                if (ContextCompat.checkSelfPermission(MineInfoActivity.this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(MineInfoActivity.this, new String[]{Manifest.permission.CAMERA},
                            EverythingConstant.RequestAndResultCode.PERMISSION_CAMERA);
                } else {
                    doHandlerPhoto(PIC_FROM_CAMERA);// 用户点击了从照相机获取
                    mPopupWindow.dismiss();
                }
                break;
            case R.id.cancle:
                mPopupWindow.dismiss();
                break;
        }
    }

    /**
     * 启动裁剪
     */
    private void cropImageUriByTakePhoto() {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(photoUri, "image/*");
        setIntentParams(intent);
        startActivityForResult(intent, PIC_FROM＿LOCALPHOTO);
    }

    /**
     * 根据不同方式选择图片设置ImageView
     *
     * @param type 0-本地相册选择，非0为拍照
     */
    private void doHandlerPhoto(int type) {
        try {
            //保存裁剪后的图片文件
            File pictureFileDir = new File(Environment.getExternalStorageDirectory(), "/upload");
            if (!pictureFileDir.exists()) {
                pictureFileDir.mkdirs();
            }
            File picFile = new File(pictureFileDir, mPhoneNum + "upload.jpeg");
            if (!picFile.exists()) {
                picFile.createNewFile();
            }
            photoUri = Uri.fromFile(picFile);
            if (type == PIC_FROM＿LOCALPHOTO) {
                Intent intent = getCropImageIntent();
                startActivityForResult(intent, PIC_FROM＿LOCALPHOTO);
            } else {
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                startActivityForResult(cameraIntent, PIC_FROM_CAMERA);
            }

        } catch (Exception e) {
            Log.i("HandlerPicError", "处理图片出现错误");
        }
    }

    /**
     * 调用图片剪辑程序
     */
    public Intent getCropImageIntent() {
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        setIntentParams(intent);
        return intent;
    }

    /**
     * 设置公用参数
     */
    private void setIntentParams(Intent intent) {
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("noFaceDetection", true); // no face detection
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    }

    private PopupWindow mPopupWindow;
    private void setPopupWindows() {
        View inflate = getLayoutInflater().inflate(R.layout.activity_check_head_img, null);
        inflate.findViewById(R.id.click_local).setOnClickListener(this);
        inflate.findViewById(R.id.click_camera).setOnClickListener(this);
        inflate.findViewById(R.id.cancle).setOnClickListener(this);
        //最后一个参数为true，点击PopupWindow消失,宽必须为match，不然肯呢个会导致布局显示不完全
        mPopupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //设置外部点击无效
        mPopupWindow.setOutsideTouchable(false);
        //设置背景变暗
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.7f;
        getWindow().setAttributes(lp);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        //设置popupwindows动画
        mPopupWindow.setAnimationStyle(R.style.AnimFromButtomToTop);
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        BitmapDrawable bitmapDrawable = new BitmapDrawable();
        mPopupWindow.setBackgroundDrawable(bitmapDrawable);
        mPopupWindow.showAtLocation(inflate, Gravity.BOTTOM, 0, 0);
    }
    /**
     * 从小到大打开动画
     */
    private void animFromSmallToBigIN() {
        overridePendingTransition(R.anim.magnify_fade_in, R.anim.fade_out);
    }
    /**
     * 从大到小结束动画
     */
    private void animFromBigToSmallOUT() {
        overridePendingTransition(R.anim.fade_in, R.anim.big_to_small_fade_out);
    }

    @Override
    public void onBackPressed() {
        finish();
        animFromBigToSmallOUT();
    }
}
